package com.zhdl.modules.common.warn.service.impl;

import com.project.common.service.impl.BaseServiceImpl;
import com.zhdl.modules.common.warn.entity.WarnRecords;
import com.zhdl.modules.common.warn.repository.WarnRecordsDao;
import com.zhdl.modules.common.warn.service.WarnRecordsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class WarnRecordsServiceImpl extends BaseServiceImpl<String, WarnRecords, WarnRecordsDao> implements WarnRecordsService {

    @Resource
    private WarnRecordsDao warnRecordsDao;


    /**
     * 保存报警状态
     *
     * @param warnRecords 每一条都保存
     * @return /
     */
    @Override
    public List<WarnRecords> saveManyWarn(List<WarnRecords> warnRecords) {
        if (warnRecords == null || warnRecords.isEmpty()) {
            return null;
        }
        List<WarnRecords> saveContent = new ArrayList<>();
        for (WarnRecords warnRecord : warnRecords) {
            //注 根据报警地址查询 并且 01为报警未复位
            WarnRecords byWarnAddress = warnRecordsDao.findByWarnAddress(warnRecord.getWarnAddress(), "01");
            if (byWarnAddress == null) {
                warnRecord.setId(UUID.randomUUID().toString());
                saveContent.add(warnRecord);
            } else {
                log.debug("当前报警地址:{}正在报警，无需重复保存", warnRecord.getWarnAddress());
            }
        }
        return warnRecordsDao.saveAll(saveContent);
    }

    /**
     * 更新报警状态 -> 报警复位
     *
     * @param warnRecords 报警状态
     * @return /
     */
    @Override
    public List<WarnRecords> updateManyWarn(List<WarnRecords> warnRecords) {
        if (warnRecords == null || warnRecords.isEmpty()) {
            return null;
        }
        List<WarnRecords> saveContent = new ArrayList<>();
        for (WarnRecords warnRecord : warnRecords) {
            //注 根据报警地址查询 并且 01为报警未复位
            WarnRecords byWarnAddress = warnRecordsDao.findByWarnAddress(warnRecord.getWarnAddress(), "01");
            if (byWarnAddress != null) {
                byWarnAddress.setOperationType("10");
                saveContent.add(byWarnAddress);
            } else {
                log.debug("当前报警地址:{}无报警，无需更改报警状态", warnRecord.getWarnAddress());
            }
        }
        if (saveContent.isEmpty()) {
            return null;
        } else {
            return warnRecordsDao.saveAll(saveContent);
        }
    }

    /**
     * 查询所有报警记录List
     */
    @Override
    public List<WarnRecords> findAllWarnRecords() {
        return warnRecordsDao.findAll();
    }

}
